package com.study.blog.controller;

import com.study.blog.common.result.BaseResponse;
import com.study.blog.model.dto.ArticleDTO;
import com.study.blog.model.entity.Article;
import com.study.blog.model.vo.ArticleVO;
import com.study.blog.service.impl.ArticleServiceImpl;
import com.study.blog.utils.CopyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Api(tags = "文章管理")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleServiceImpl articleService;

    /**
     * 根据id查询指定文章
     *
     * @param id 文章id
     * @return ArticleVo
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取指定文章")
    @ApiImplicitParam(name = "id", value = "文章id", required = true)
    public BaseResponse<ArticleVO> getArticleById(@PathVariable String id) {
        ArticleVO article = articleService.getArticleById(id);
        return BaseResponse.success(article);
    }

    /**
     * 查询所有的文章
     *
     * @return List<ArticleVo>
     */
    @ApiOperation(value = "获取所有文章")
    @GetMapping("/list")
    public BaseResponse<List<ArticleVO>> getList() {
        return BaseResponse.success(articleService.getAll());
    }


    /**
     * 新增一篇文章
     *
     * @param articleDTO 文章的相关信息
     * @return BaseResponse
     */
    @ApiOperation(value = "新增文章")
    @PostMapping("")
    public BaseResponse<String> add(@RequestBody @Validated ArticleDTO articleDTO) {
        Article article = CopyUtil.copy(articleDTO, Article.class);
        articleService.insert(article);
        return BaseResponse.success("新增成功");
    }

    /**
     * 修改指定文章
     *
     * @param articleDTO 文章的相关信息
     * @return BaseResponse
     */
    @ApiOperation(value = "修改文章")
    @PatchMapping("")
    public BaseResponse<String> update(@RequestBody ArticleDTO articleDTO) {
        Article article = CopyUtil.copy(articleDTO, Article.class);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer update = articleService.update(article);
        return BaseResponse.success(update.toString());
    }

    /**
     * 删除指定id的文章
     *
     * @param id 文章id
     * @return BaseResponse
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除指定文章")
    @ApiImplicitParam(name = "id", value = "文章id", required = true)
    public BaseResponse<String> remove(@PathVariable Long id) {
        Integer remove = articleService.remove(id);
        return BaseResponse.success(remove.toString());
    }

}
